﻿using CefDemo.utils;
using CefSharp;
using CefSharp.WinForms;
using System;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace CefDemo.cef
{
    public static class ChromeBrowserExtensions
    {
        public static void BindObject<T>(this ChromiumWebBrowser browser, string name,
            AbstractBindObject<T> objectToBind, bool isAsync = false) where T : Control
        {
            browser.JavascriptObjectRepository.Register(name, objectToBind, isAsync: isAsync,
                options: BindingOptions.DefaultBinder);
        }

        public static void ExecuteJsAsync(this ChromiumWebBrowser browser, string funcName, object param)
        {
            var arg = param == null ? "" : JSON.toJSON(param);
            browser.ExecuteScriptAsync(funcName, arg);
        }

        public static async Task<T> EvaluateJsAsync<T>(this ChromiumWebBrowser browser, string funcName, object param)
        {
            try
            {
                var arg = param == null ? "" : JSON.toJSON(param);
                var result = await browser.EvaluateScriptAsync(funcName, arg);
                if (result.Success)
                {
                    var ttt = result.Result;
                    var typeName = typeof(T).Name;
                    if (typeName.EqualIgnoreCase("string") || typeName.EqualIgnoreCase("int") || typeName.EqualIgnoreCase("double"))
                    {
                        return (T)ttt;
                    }
                    return JSON.parseJSON<T>(ttt as string);
                }
                return default;
            }
            catch (Exception exc)
            {
                Console.WriteLine(exc.Message);
                return default;
            }
        }
    }
}
